{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 64,
   "metadata": {},
   "outputs": [],
   "source": [
    "from __future__ import absolute_import\n",
    "from __future__ import division\n",
    "from __future__ import print_function\n",
    "\n",
    "import argparse\n",
    "import sys\n",
    "\n",
    "from tensorflow.examples.tutorials.mnist import input_data\n",
    "\n",
    "import tensorflow as tf\n",
    "#import tensorflow.initializers as initializers"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 65,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Extracting D:\\CSDN\\week6\\tensorflow-without-a-phd-master\\train-images-idx3-ubyte.gz\n",
      "Extracting D:\\CSDN\\week6\\tensorflow-without-a-phd-master\\train-labels-idx1-ubyte.gz\n",
      "Extracting D:\\CSDN\\week6\\tensorflow-without-a-phd-master\\t10k-images-idx3-ubyte.gz\n",
      "Extracting D:\\CSDN\\week6\\tensorflow-without-a-phd-master\\t10k-labels-idx1-ubyte.gz\n"
     ]
    }
   ],
   "source": [
    "data_dir = r'D:\\CSDN\\week6\\tensorflow-without-a-phd-master'\n",
    "mnist = input_data.read_data_sets(data_dir,one_hot=True)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 66,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "x = tf.placeholder(tf.float32, [None, 784])\n",
    "y_ = tf.placeholder(tf.float32, [None, 10])\n",
    "learning_rate = tf.placeholder(tf.float32)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 67,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "with tf.name_scope('reshape'):\n",
    "  x_image = tf.reshape(x, [-1, 28, 28, 1])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 68,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "with tf.name_scope('conv1'):\n",
    "  h_conv1 = tf.contrib.slim.conv2d(x_image, 32, [5,5],\n",
    "                             padding='SAME',weights_initializer=tf.contrib.layers.xavier_initializer(),\n",
    "                             activation_fn=tf.nn.relu)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 69,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "with tf.name_scope('pool1'):\n",
    "  h_pool1 = tf.contrib.slim.max_pool2d(h_conv1, [2,2], stride=2, \n",
    "                         padding='VALID')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 70,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# Second convolutional layer -- maps 32 feature maps to 64.\n",
    "with tf.name_scope('conv2'):\n",
    "  h_conv2 = tf.contrib.slim.conv2d(h_pool1, 64, [5,5],\n",
    "                             padding='SAME',weights_initializer=tf.contrib.layers.xavier_initializer(),\n",
    "                             activation_fn=tf.nn.relu)\n",
    "\n",
    "# Second pooling layer.\n",
    "with tf.name_scope('pool2'):\n",
    "  h_pool2 = tf.contrib.slim.max_pool2d(h_conv2, [2,2],\n",
    "                        stride=[2, 2], padding='VALID')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 再增加一层卷积层发现训练效果更好"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 71,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "with tf.name_scope('conv3'):\n",
    "  h_conv3 = tf.contrib.slim.conv2d(h_pool2, 128, [4,4],\n",
    "                             padding='SAME',weights_initializer=tf.contrib.layers.xavier_initializer(),\n",
    "                             activation_fn=tf.nn.relu)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 72,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "TensorShape([Dimension(7), Dimension(7)])"
      ]
     },
     "execution_count": 72,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "h_pool2.shape[1:3]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 73,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "\n",
    "# Fully connected layer 1 -- after 2 round of downsampling, our 28x28 image\n",
    "# is down to 7x7x64 feature maps -- maps this to 1024 features.\n",
    "with tf.name_scope('fc1'):\n",
    "  h_pool2_flat = tf.contrib.slim.avg_pool2d(h_conv3, h_pool2.shape[1:3],\n",
    "                        stride=[1, 1], padding='VALID')\n",
    "  h_fc1 = tf.contrib.slim.conv2d(h_pool2_flat, 1024, [1,1], activation_fn=tf.nn.relu)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 74,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# Dropout - controls the complexity of the model, prevents co-adaptation of\n",
    "# features.\n",
    "with tf.name_scope('dropout'):\n",
    "    keep_prob = tf.placeholder(tf.float32)\n",
    "    h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)\n",
    "\n",
    "# Map the 1024 features to 10 classes, one for each digit\n",
    "with tf.name_scope('fc2'):\n",
    "  y = tf.squeeze(tf.contrib.slim.conv2d(h_fc1_drop, 10, [1,1], activation_fn=None))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 75,
   "metadata": {},
   "outputs": [],
   "source": [
    "cross_entropy = tf.reduce_mean(\n",
    "    tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=y))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 以前是 7e-5，看数据有点过拟合，改成8e-5"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 76,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "l2_loss = tf.add_n([tf.nn.l2_loss(w) for w in tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES)] )\n",
    "total_loss = cross_entropy  + 8e-5*l2_loss\n",
    "train_step = tf.train.GradientDescentOptimizer(learning_rate).minimize(total_loss)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 77,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "sess = tf.Session()\n",
    "init_op = tf.global_variables_initializer()\n",
    "sess.run(init_op)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 以前的模板学习率是0.01，发现调成 0.1 效果更好"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 78,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "step 100, entropy loss: 2.290374, l2_loss: 941.555054, total loss: 2.365698\n",
      "0.22\n",
      "0.225\n",
      "step 200, entropy loss: 2.143594, l2_loss: 941.543274, total loss: 2.218918\n",
      "0.25\n",
      "0.22\n",
      "step 300, entropy loss: 1.964320, l2_loss: 943.208984, total loss: 2.039777\n",
      "0.36\n",
      "0.3225\n",
      "step 400, entropy loss: 2.159480, l2_loss: 946.203857, total loss: 2.235177\n",
      "0.26\n",
      "0.3006\n",
      "step 500, entropy loss: 1.289182, l2_loss: 955.372803, total loss: 1.365612\n",
      "0.64\n",
      "0.6007\n",
      "step 600, entropy loss: 0.593871, l2_loss: 966.431396, total loss: 0.671185\n",
      "0.85\n",
      "0.8438\n",
      "step 700, entropy loss: 0.422142, l2_loss: 972.061890, total loss: 0.499907\n",
      "0.93\n",
      "0.9222\n",
      "step 800, entropy loss: 0.300180, l2_loss: 976.787964, total loss: 0.378323\n",
      "0.95\n",
      "0.9137\n",
      "step 900, entropy loss: 0.274739, l2_loss: 979.290161, total loss: 0.353082\n",
      "0.92\n",
      "0.9406\n",
      "step 1000, entropy loss: 0.223858, l2_loss: 981.491516, total loss: 0.302377\n",
      "0.95\n",
      "0.9412\n",
      "step 1100, entropy loss: 0.203124, l2_loss: 982.761047, total loss: 0.281744\n",
      "0.96\n",
      "0.9521\n",
      "step 1200, entropy loss: 0.176466, l2_loss: 983.863281, total loss: 0.255175\n",
      "0.98\n",
      "0.9552\n",
      "step 1300, entropy loss: 0.169514, l2_loss: 984.817505, total loss: 0.248300\n",
      "0.98\n",
      "0.9555\n",
      "step 1400, entropy loss: 0.157154, l2_loss: 985.612793, total loss: 0.236003\n",
      "0.99\n",
      "0.9541\n",
      "step 1500, entropy loss: 0.130495, l2_loss: 986.023804, total loss: 0.209377\n",
      "0.98\n",
      "0.9556\n",
      "step 1600, entropy loss: 0.123773, l2_loss: 986.632202, total loss: 0.202703\n",
      "0.97\n",
      "0.9598\n",
      "step 1700, entropy loss: 0.156865, l2_loss: 987.095093, total loss: 0.235832\n",
      "0.98\n",
      "0.9556\n",
      "step 1800, entropy loss: 0.067837, l2_loss: 987.312317, total loss: 0.146822\n",
      "1.0\n",
      "0.9703\n",
      "step 1900, entropy loss: 0.122205, l2_loss: 987.560791, total loss: 0.201210\n",
      "0.98\n",
      "0.9694\n",
      "step 2000, entropy loss: 0.132317, l2_loss: 987.633423, total loss: 0.211328\n",
      "0.99\n",
      "0.9698\n",
      "step 2100, entropy loss: 0.068106, l2_loss: 987.463623, total loss: 0.147103\n",
      "0.98\n",
      "0.9711\n",
      "step 2200, entropy loss: 0.243454, l2_loss: 987.810974, total loss: 0.322479\n",
      "0.96\n",
      "0.9705\n",
      "step 2300, entropy loss: 0.053443, l2_loss: 987.632080, total loss: 0.132453\n",
      "0.99\n",
      "0.9737\n",
      "step 2400, entropy loss: 0.157619, l2_loss: 987.674988, total loss: 0.236633\n",
      "0.97\n",
      "0.9644\n",
      "step 2500, entropy loss: 0.055168, l2_loss: 987.506409, total loss: 0.134168\n",
      "1.0\n",
      "0.9754\n",
      "step 2600, entropy loss: 0.079672, l2_loss: 987.368164, total loss: 0.158661\n",
      "0.98\n",
      "0.9761\n",
      "step 2700, entropy loss: 0.061467, l2_loss: 987.036072, total loss: 0.140430\n",
      "1.0\n",
      "0.9774\n",
      "step 2800, entropy loss: 0.092334, l2_loss: 986.920105, total loss: 0.171287\n",
      "0.98\n",
      "0.9755\n",
      "step 2900, entropy loss: 0.064848, l2_loss: 986.746887, total loss: 0.143788\n",
      "0.98\n",
      "0.975\n",
      "step 3000, entropy loss: 0.040917, l2_loss: 986.388184, total loss: 0.119828\n",
      "1.0\n",
      "0.9771\n",
      "step 3100, entropy loss: 0.055930, l2_loss: 986.052612, total loss: 0.134814\n",
      "1.0\n",
      "0.9773\n",
      "step 3200, entropy loss: 0.063146, l2_loss: 985.653198, total loss: 0.141998\n",
      "0.99\n",
      "0.9786\n",
      "step 3300, entropy loss: 0.073182, l2_loss: 985.057678, total loss: 0.151987\n",
      "0.99\n",
      "0.9789\n",
      "step 3400, entropy loss: 0.090751, l2_loss: 984.832336, total loss: 0.169537\n",
      "0.98\n",
      "0.9773\n",
      "step 3500, entropy loss: 0.115643, l2_loss: 984.530396, total loss: 0.194405\n",
      "1.0\n",
      "0.9782\n",
      "step 3600, entropy loss: 0.091578, l2_loss: 984.167725, total loss: 0.170312\n",
      "0.99\n",
      "0.978\n",
      "step 3700, entropy loss: 0.028190, l2_loss: 983.681519, total loss: 0.106885\n",
      "1.0\n",
      "0.9808\n"
     ]
    }
   ],
   "source": [
    "# Train\n",
    "for step in range(3700):\n",
    "  batch_xs, batch_ys = mnist.train.next_batch(100)\n",
    "  lr = 0.1\n",
    "  _, loss, l2_loss_value, total_loss_value = sess.run(\n",
    "               [train_step, cross_entropy, l2_loss, total_loss], \n",
    "               feed_dict={x: batch_xs, y_: batch_ys, learning_rate:lr, keep_prob:0.5})\n",
    "  \n",
    "  if (step+1) % 100 == 0:\n",
    "    print('step %d, entropy loss: %f, l2_loss: %f, total loss: %f' % \n",
    "            (step+1, loss, l2_loss_value, total_loss_value))\n",
    "    # Test trained model\n",
    "    correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))\n",
    "    accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\n",
    "    print(sess.run(accuracy, feed_dict={x: batch_xs, y_: batch_ys, keep_prob:1}))\n",
    "  if (step+1) % 100 == 0:\n",
    "    print(sess.run(accuracy, feed_dict={x: mnist.test.images,\n",
    "                                    y_: mnist.test.labels, keep_prob:1}))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 79,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0.9808\n"
     ]
    }
   ],
   "source": [
    "print(sess.run(accuracy, feed_dict={x: mnist.test.images, y_: mnist.test.labels, keep_prob:1}))"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
